package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.TagsServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Tags;
import com.hxkj.domain.po.WebsiteAddr;
import com.hxkj.utils.TemplateModelUtils;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName HotTagsDirrective 热词标签、tags聚合
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/7/20 11:28
 * @Version 1.0
 */
@Component
@Log4j
public class TagsDirective extends AbstractDirective {

    @Autowired
    private TagsServiceClient tagsServiceClient;

    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，是否排序,0：升序，1：降序
     */
    public static final String SORT = "sort";
    /**
     * 输入参数，获取参数条数
     */
    public static final String COUNT = "count";
    /**
     * 输入参数，排序的字段，多个用","隔开
     */
    public static final String SORT_KEY = "sortKey";


    /**
     * 聚合tags的列表
     */
    public static final String POLY_TAGS_LIST = "polyTagsList";
    /**
     * 热词tags的列表
     */
    public static final String HOT_TAGS = "hotTagsList";

    /**
     * 热词tags分页
     */
    public static final String HOT_TAGS_PAGE = "pageInfo";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            //Mr.zheng:获取参数
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) super.getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            //Mr.zheng:默认根据降序排序
            String sort = super.getString(SORT, params) == null ? "quote_count DESC" : super.getString(SORT, params);
            //Mr.zheng:默认根据热度"heat"排序
            String sortkey = super.getString(SORT_KEY, params) == null ? "quote_count DESC" : super.getString(SORT_KEY, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? 20 : super.getInt(COUNT, params);


            String note = super.getNote(env);

            //Mr.zheng:封装查询参数
            Tags tags = new Tags();
            tags.setSortkey(sortkey);
            tags.setSort(sort);
            tags.setSiteId(siteId);
            tags.setCount(count);

            ResultPageStruct<Tags> resultPageStruct = getTagsResultPageStruct(tags);
            List<Tags> hotTagsList = resultPageStruct.getData();
            PageTo pageInfo = resultPageStruct.getPageInfo();
            pageInfo.setCondition(sort);
            List<Tags> polyTagsList = tagsServiceClient.getShowTagsList(tags);

            if (StringUtils.isNotBlank(note)) {
                WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
                tags.setManuscriptPath(websiteAddr.getIpAdd() + tags.getManuscriptPath());
                for (Tags tags1 : hotTagsList) {
                    tags1.setManuscriptPath(websiteAddr.getIpAdd() + tags1.getManuscriptPath());
                }
                for (Tags tags2 : polyTagsList) {
                    tags2.setManuscriptPath(websiteAddr.getIpAdd() + tags2.getManuscriptPath());
                }
            }else {
                // 静态文件文章链接加前缀
                Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                String urlContext = siteCtxMap.get(siteId);
                if(StringUtils.isNotBlank(urlContext)) {
                    tags.setManuscriptPath(urlContext + tags.getManuscriptPath());
                    for (Tags item : hotTagsList) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                    for (Tags item : polyTagsList) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
            }

            env.setVariable(HOT_TAGS, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(hotTagsList));
            env.setVariable(HOT_TAGS_PAGE, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(pageInfo));
            env.setVariable(POLY_TAGS_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(polyTagsList));

            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("热点标签所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
